package master

import (
	"context"
	"fmt"
	"log"
	"study-crontab/crontab/common"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type LogMgr struct {
	client         *mongo.Client
	logCollection  *mongo.Collection
	logChan        chan *common.JobLog
	autoCommitChan chan *common.LogBatch
}

var G_logMgr *LogMgr

func InitLogMgr() (err error) {
	clientOptions := options.Client().ApplyURI(G_config.MongodbUri).
		SetTimeout(time.Duration(G_config.MongodbConnectTimeout) * time.Millisecond)
	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	G_logMgr = &LogMgr{
		client:        client,
		logCollection: client.Database("cron").Collection("log"),
	}
	fmt.Println("Connected to MongoDB!")
	return
}

func (logMgr *LogMgr) ListLog(name string, skip, limit int) (logArr []*common.JobLog, err error) {
	var (
		cursor *mongo.Cursor
		jobLog *common.JobLog
	)
	logArr = make([]*common.JobLog, 0)
	filter := &common.LogFiller{JobName: name}
	//按照任务开始条件倒排
	logSort := &common.SortLogByStartTime{SortOrder: -1}
	cursor, err = logMgr.logCollection.Find(context.TODO(), filter,
		options.Find().SetSort(logSort),
		options.Find().SetSkip(int64(skip)),
		options.Find().SetLimit(int64(limit)))
	if err != nil {
		return
	}
	defer cursor.Close(context.TODO())
	//遍历游标获取结果数据
	for cursor.Next(context.TODO()) {
		jobLog = &common.JobLog{}
		//反序列化Bson到对象
		if cursor.Decode(&jobLog) != nil {
			fmt.Println(err)
			continue
		}
		logArr = append(logArr, jobLog)
	}
	return
}
